<!--
 * @Author: 1453937336@qq.com 1453937336@qq.com
 * @Date: 2024-04-17 18:08:26
 * @LastEditors: 1453937336@qq.com 1453937336@qq.com
 * @LastEditTime: 2024-07-10 13:41:28
 * @FilePath: \itforce_hris\src\views\system\dept\component\corporate-information.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="unit-information">
    <template v-if="!ifEmployee">
      <a-row>
        <a-col :span="24" style="display: flex;align-items: center;">
          <svg-icon name="department" />
          <span class="subTitle">{{ ifPosition ? $t("职位详情") : `${$t("组织")} ${$t("单元信息")}` }}</span>
        </a-col>
        <a-col :span="24" style="margin-top: 16px;">
          <a-row style="margin-top: 16px;">
            <a-col :span="3" class="lable">{{ $t("简称") }}</a-col>
            <a-col :span="5" class="context">{{ unitDetail?.shortNameEn || unitDetail?.shortName}}</a-col>
            <a-col :span="3" class="lable">{{ $t("名称") }}</a-col>
            <a-col :span="5" class="context">{{ unitDetail?.nameEn || unitDetail?.name}}</a-col>
            <a-col :span="7" v-if="!ifPosition" style="display: flex;justify-content: flex-end;" v-permission="['modifyFlag']">
              <EditOutlined @click="onUnitCilck"/>
            </a-col>
          </a-row>
          <a-row style="margin-top: 16px;">
            <a-col :span="3" class="lable">{{ $t("领导") }}</a-col>
            <a-col :span="5" class="context">{{ employeeName(unitDetail?.leader) }}</a-col>
            <a-col :span="3" class="lable">{{ $t("唯一编码") }}</a-col>
            <a-col :span="5" class="context">{{ unitDetail?.uniqueCode }}</a-col>
          </a-row>
          <a-row style="margin-top: 16px;">
            <a-col :span="3" class="lable">{{ $t("单元描述") }}</a-col>
            <a-col :span="5" class="context">{{ unitDetail?.description }}</a-col>
          </a-row>
        </a-col>
      </a-row>

      <a-row style="margin-top: 24px;" v-if="!ifPosition">
        <a-col :span="24" style="display: flex;align-items: center;">
          <i class="fa fa-cogs" style="color: #A7B1C2;"/>
          <span class="subTitle">{{ $t("下级单元信息") }}</span>
        </a-col>
        <a-col :span="24" style="margin-top: 16px;">
          <Table
            ref="Tabular"
            :tableDatas="unitListData"
            :loading="loading"
            :isPagenation="false"
            :columns="unitColumns"
            
          >
            <template #unitTypeIcon="{ row, index }">
              <svg-icon :name="row.unitTypeIcon" />
            </template>
            <template #shortNameEn="{ row, index }">
              <span>{{ isCn ? row.shortNameZh : isArabic ? row.shortNameAr : row.shortNameEn }}</span>
            </template>
            <template #nameZh="{ row, index }">
              <span>{{ isCn ? row.nameZh : isArabic ? row.nameAr : row.nameEn }}</span>
            </template>
            <template #leader="{ row, index }">
              <span>{{ employeeName(row.leader) }}</span>
            </template>
          </Table>
        </a-col>
      </a-row>

      <a-row style="margin-top: 24px;">
        <a-col :span="24" style="display: flex;align-items: center;">
          <svg-icon width="20" height="20" name="card"></svg-icon>
          <span class="subTitle">{{ $t("职位") }}</span>
        </a-col>
        <a-col :span="24" style="margin-top: 16px;">
          <Table
            ref="Tabular"
            :tableDatas="positionListData"
            :loading="positionLoading"
            :isPagenation="false"
            :columns="positionColumns"
          >
          <template #positionType="{ row, index }">
            {{ getListName(row.positionType, positionTypeList) || '-' }}
          </template>
          <template #employeeCount="{ row, index }">
            <a @click="employeeClick(row)">{{ row.employeeCount || ''}}</a>
          </template>
        </Table>
        </a-col>
      </a-row>
    </template>
    <template v-if="ifEmployee">
      <div style="display: flex;justify-content: flex-end;cursor: pointer;" @click="closeEmployee"><i class="fa fa-times" /></div>
      <positionEmployee  ref="employeeModalRed" :companyId="props.companyId" :positionData="positionData"/>
    </template>
    

    <unitUpdateModal ref="unitModalRef" :lineManagerList="lineManagerList" @updateUnitModal="updateUnitModal" @DeleteUnitModal="DeleteUnitModal"/>
  </div>
</template>
<script setup>
import Table from "@/components/Table/index.vue";
import { reactive, computed,ref, watch, defineProps, nextTick, onMounted, getCurrentInstance } from "vue";
import { BankFilled, EditOutlined, DeploymentUnitOutlined, TeamOutlined, ContactsOutlined } from '@ant-design/icons-vue';
import positionEmployee from '@/pages/staff/staffPage/components/position/positionDetailTable.vue'
import unitUpdateModal from "./unit-update-modal.vue";
import { GetEmployee } from "@/api/organization/index";
import { useI18n } from 'vue-i18n';
import { useLanguage } from "@/hooks/index"
import hooks, { employeeStore } from "@/hooks/index";
const { isEn, isCn, isArabic } = useLanguage()
const { t: $t } = useI18n();
import { useStore } from "vuex";
import { GetBatchCodeDict } from "@/api/public"
import { GetBusinessUnit, GetBusinessUnitDetails, GetPositionList, GetPositionInfo, GetPositionContractList } from "@/api/organization/index";
const emits = defineEmits(['updateunitInformation', 'employeeClose'])
const store = useStore();
const props = defineProps({
  unitObj: { type: Object, default: {} },
  companyId: { type: Number, default: null }
});

const ifEmployee = ref(false)

const unitColumns = [
  { title: '', dataIndex: 'unitTypeIcon', key: 'unitTypeIcon', slot: "unitTypeIcon", width: 50 },
  { 
    title: () => {
      return (
        $t('简称')
      )
    },
    dataIndex: 'shortNameEn',
    key: 'shortNameEn',
    align: 'left'
  },
  { 
    title: () => {
      return (
        $t('名称')
      )
    },
    dataIndex: 'nameEn',
    key: 'nameEn',
    align: 'left' 
  },
  { 
    title: () => {
      return (
        $t('领导')
      )
    },
    dataIndex: 'leader',
    key: 'leader',
    align: 'left' 
  }
];

const positionColumns = [
  { 
    title: () => {
      return (
        $t('名称')
      )
    },
    dataIndex: 'name',
    key: 'name',
    align: 'left' 
  },
  {
    title: () => {
      return (
        $t('岗位类型')
      )
    },
    dataIndex: 'positionType',
    key: 'positionType',
    slot: "positionType",
    align: 'center'
  },
  { 
    title: () => {
      return (
        $t('描述')
      )
    },
    dataIndex: 'description',
    key: 'description',
    align: 'left' 
  },
  {
    title: () => {
      return (
        $t('员工数量')
      )
    },
    dataIndex: 'employeeCount',
    key: 'employeeCount',
    slot: "employeeCount",
    align: 'center'
  }
]
// 使用watch来监听对象
watch(() => props.unitObj, async (newVal) => {
  console.log('使用watch来监听对象props.unitObj', newVal)
    if (newVal && newVal.uuid) {
      if (newVal.isVirtual) {
        getPositionDetails(newVal.uuid)
        getPositionContractList(newVal.uuid)
      } else {
        getUnitDetails(newVal.uuid)
        getUnitList(Number(newVal.id))
        getPostList(Number(newVal.id))
      }
      getEmployeeList()
      getCode()
      employeeStore.useEmployeeHook.buid = newVal.id // buid
    }
    
  },
  {
    flush: 'post',
    // deep: ture,
    // immediate: true
  }
);

// 查职位详情
const getPositionDetails = async (uuid) => {
  const { data } = await GetPositionInfo(uuid)
  nextTick(() => {
    unitDetail.value = data ?? {}
  })
}

const ifPosition = computed(() => {
  return props.unitObj.isVirtual
})

const lineManagerList = ref([])
const getEmployeeList = async () => {
  const { data } = await GetEmployee({ enterpriseId: props.unitObj.enterpriseId })
  nextTick(() => {
    lineManagerList.value = data ?? []
  })
}
const employeeName = (val) => {
  if (val) {
    const i = JSON.parse(val)
    let list = []
    let name = ''
    list = lineManagerList.value.filter(item => {
      if (i.includes(Number(item.id))) return true
    })
    name = list.map(v => v.fullName)
    return name.join(',')
  }
}
onMounted(() => {
})

const init = (obj) => {
  getUnitDetails(obj.uuid)
  getUnitList(Number(obj.id))
  getPostList(Number(obj.id))
  getCode()
}
// 单元弹框
const unitModalRef = ref(null)
const onUnitCilck = () => {
  if (unitModalRef.value) unitModalRef.value.showModal(unitDetail.value)
}
// 单元详情
const unitDetail = ref({})
const getUnitDetails = (uuid) => {
  GetBusinessUnitDetails({
    uuid: uuid
  }).then(res => {
    nextTick(() => {
      unitDetail.value = res.data
    })
  })
}

const positionTypeList = ref([])
const getCode = () => {
  GetBatchCodeDict({
    dictKey: 'positionType'
  }).then(res => {
    if (res.code !== 200) return
    positionTypeList.value = res.data.positionType
  })
}
const getListName = (val, codeValue) => {
  let name = null;
  let obj = null;
  if (val || val === 0) {
    obj = codeValue.find((item) => {
      if (item.dictData == String(val)) return item;
    });
    name = isCn.value ? obj?.descZh : isArabic.value ? obj?.descAr : obj?.dictDesc;
  }
  return name;
};
const updateUnitModal = (parentId, id) => {
  getUnitDetails(props.unitObj.uuid)
  emits('updateUnitInformationRefresh', parentId, id)
}
const DeleteUnitModal = () => {
  emits('DeleteUnitModal')
}

// 下级单元
const loading = ref(false)
const unitListData = ref([])
const getUnitList = (id) => {
  loading.value = true
  GetBusinessUnit({
    parentId: id
  }).then(res => {
    nextTick(() => {
      unitListData.value = res.data
    })
  }).finally(() => {
    loading.value = false
  });
}

// 职位
const positionListData = ref([])
const positionLoading = ref(false)
const getPostList = (id) => {
  positionLoading.value = true
  GetPositionList({
    enterpriseId: props.unitObj.enterpriseId,
    buId: id
  }).then(res => {
    nextTick(() => {
      positionListData.value = res.data
    })
  }).finally(() => {
    positionLoading.value = false
  });
}
// 根据名义岗位uuid查询实际岗位列表
const getPositionContractList = async (uuid) => {
  positionLoading.value = true
  const { data } =  await GetPositionContractList(uuid).finally(() => { positionLoading.value = false });
  nextTick(() => {
    positionListData.value = data
  })
}


const positionData = ref(null)
const employeeClick = (row) => {
  if (row.employeeCount === 0) return
  ifEmployee.value = true
  emits('employeeClose', ifEmployee.value)
  positionData.value = row // 职位id
  employeeStore.useEmployeeHook.closeStatus = true
}
const closeEmployee = () => {
  ifEmployee.value = false
  emits('employeeClose', ifEmployee.value)
}
defineExpose({
  init
});
</script>
<style lang="scss" scoped>
.unit-information {
  margin-top: 16px;
}
.lable {
  color: #a7b1c2;
  font-size: 12px;
}
.context {
  color: #686a6c;
  font-size: 12px;
}
.subTitle {
  margin-left: 8px;
  margin-right: 8px;
  font-size: 14px;
  font-weight: bold;
  color: #676a6c;
}
::v-deep {
  .ant-table-wrapper  .ant-table {
    font-size: 12px !important;
  }
  .ant-table-wrapper .ant-table-container table>thead>tr:first-child >*:first-child {
      border-start-start-radius: 0px;
  }
  .ant-table-wrapper .ant-table-container table>thead>tr:first-child >*:last-child {
      border-start-end-radius: 0px;
  }
}  
</style>
